import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:sinosheets/components/gb_alert.dart';
import 'package:sinosheets/network/api.dart';
import 'package:sinosheets/route/route_utils.dart';
import 'package:sinosheets/utils/common_utils/log_util.dart';
import 'package:sinosheets/utils/storage/LSUtil.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:sinosheets/utils/theme/style_utils.dart';
import 'package:sinosheets/utils/toast_util.dart';
import 'package:sinosheets/utils/turbolink_utils.dart';

///公共参数类
class AppPrefix {
  static final String _env = LSUtil.getAppEnv();

  ///获取API前缀
  static String get apiPrefix {
    switch (_env) {
      case "test":
        return "https://api.xbuy.tech";
      case "dev":
        return "http://192.168.0.27:9205";
      case "prod":
      default:
        return "https://www.sinosheets.com/api";
    }
  }

  /// 获取H5前缀
  static String get h5Prefix {
    switch (_env) {
      case "test":
        return "https://app.xbuy.tech";
      case "dev":
        return "http://192.168.0.116:8080";
      case "prod":
      default:
        return "https://app.itaobuy.com";
    }
  }

  static String get urlPrefix {
    switch (_env) {
      case "test":
        return "https://www.xbuy.tech";
      case "dev":
        return "http://192.168.0.116:8080";
      case "prod":
      default:
        return "https://www.itaobuy.com";
    }
  }

  static String get seagoUrl {
    switch (_env) {
      case "test":
        return "https://sheet.xbuy.tech/seago";
      case "dev":
        return "https://seago.xbuy.tech/seago";
      case "prod":
      default:
        return "https://sinosheets.com/seago";
    }
  }

  /// 获取H5调试模式
  static bool get h5Debug {
    switch (_env) {
      case "test":
        return true;
      case "dev":
        return true;
      case "prod":
      default:
        return false;
    }
  }
}

///主要配置App启动时的一些初始化项
///包含第三方库的初始化，全局变量的初始化等
class MainConfig {
  static Future<void> init() async {
    //初始化全局变量
    LogUtil.init(isDebug: kDebugMode, tag: 'SinoSheets');
    await initLocalStorage();
    await initNetConfig();
    initWebViewConfig();
    await TurbolinkUtils.init();
  }

  ///初始化本地存储
  static Future<void> initLocalStorage() async {
    //初始化本地存储
    bool isInit = await LSUtil.init();
    if (!isInit) {
      LogUtil.e('本地存储初始化失败');
    } else {
      LogUtil.e('本地存储初始化成功');
    }
    //获取app版本号
    await getAppVersion();
  }

  // 获取应用版本信息
  static Future<void> getAppVersion() async {
    final packageInfo = await PackageInfo.fromPlatform();
    String versionName = packageInfo.version;
    LSUtil.saveAPPVersion(versionName);
  }

  ///初始化网络配置
  static Future<void> initNetConfig() async {
    //初始化网络配置
    String baseUrl = AppPrefix.apiPrefix;
    LogUtil.e('初始化URL: $baseUrl');
    HttpClient().init(baseUrl);
  }

  ///初始化webview配置
  static void initWebViewConfig() {
    //初始化webview配置
    if (Platform.isAndroid) {
      InAppWebViewController.setWebContentsDebuggingEnabled(AppPrefix.h5Debug);
    }
  }
}

///公共方法类
class GBUtils {
  ///判断是否是平板
  static bool isTablet() {
    return MediaQuery.of(Get.context!).size.shortestSide >= 600;
  }

  ///全局收键盘方法
  static void hideKeyboard() {
    FocusScope.of(Get.context!).requestFocus(FocusNode());
  }

  ///检查登录并跳转
  static bool checkLoginAndJump() {
    if (!LSUtil.getLoginStatus()) {
      // RouteUtils.openSingleLogin();
      return false;
    }
    return true;
  }

  ///获取顶部安全高度
  static double getTopSafeHeight() {
    return MediaQuery.of(Get.context!).padding.top;
  }

  ///获取底部安全高度
  static double getBottomSafeHeight() {
    double paddingBottom = LSUtil.getBottomSafeHeight();
    // 当键盘弹起时，使用 viewInsets.bottom；否则使用 padding.bottom
    return paddingBottom > 0 ? paddingBottom : 10.r;
  }

  ///复制内容到剪切板
  static void copyToClipboard(String text) {
    Clipboard.setData(ClipboardData(text: text));
    ToastUtil.showText('copy_success'.tr);
  }

  ///清空剪切板
  static void clearClipboard() {
    Clipboard.setData(ClipboardData(text: ''));
  }

  ///打开国家列表页面
  static Future<Map> openCountryPage(Map select, {bool isShowChina = true}) async {
    BaseResponse response = await ResourceApis.queryDataRegionNoPage();
    if (response.isSuccess) {
      List countries = response.data['regionVOList'] ?? [];
      List hots = response.data['hotRegionVOList'] ?? [];
      if (countries.isNotEmpty) {
        return await RouteUtils.openCountryList(countries, hots, select, isShowChina: isShowChina);
      }
    }
    return {};
  }

  /// 打开线路列表页面
  static Future<Map> openShippingLine(Map params) async {
    BaseResponse response = await LogisticsApis.estimateFreight(params);
    if (response.isSuccess) {
      List data = response.data ?? [];
      if (data.isNotEmpty) {
        return await RouteUtils.openShippingLineList(data);
      } else {
        GBAlert.show(
          title: "line_empty_title".tr,
          height: 230.r,
          content: Text(
            "line_empty_content".tr,
            style: StyleUtils.ts_33_15_400,
            maxLines: 5,
            overflow: TextOverflow.ellipsis,
          ),
          buttonType: GBAlertButtonType.oneButton,
        );
      }
    }
    return {};
  }
}
